package com.demo.camunda.util;

import com.demo.camunda.util.JWTUtil.AuthenticationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Configuration
public class WebMvcConfig   implements Filter,WebMvcConfigurer   {
    @Override
      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
             HttpServletResponse response = (HttpServletResponse) servletResponse;
              HttpServletRequest request = (HttpServletRequest)servletRequest;

              String origin = request.getHeader("Origin");
              response.setHeader("Access-Control-Allow-Origin", origin);
              response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
              response.setHeader("Access-Control-Max-Age", "3600");
              // response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
              response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token"); // 解决vue-axios请求报错问题
              response.setHeader("Access-Control-Allow-Credentials", "true");
              String method = request.getMethod();
              if(method.equalsIgnoreCase("OPTIONS")){
                     servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
                 }else{
                     filterChain.doFilter(servletRequest, servletResponse);
                 }
            }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**");    // 拦截所有请求，通过判断是否有 @LoginRequired 注解 决定是否需要登录
    }
    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}